//
//  UserInfoViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/8/18.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "UserInfoViewController.h"
#import "AddressViewController.h"
#import "LoginViewController.h"
#import "UIButton+AFNetworking.h"
#import "EditMessagePerVC.h"

@interface UserInfoViewController () <UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) UIImageView *iconImgButton;
@property (nonatomic,strong) UIButton *changeButton;
@property (nonatomic, strong) NSArray *infoArray;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleView:@"个人信息"];
    //添加一个按钮 退出当前账号
    [self tableFootview];
    self.dataArray = @[@"", @"用户名", @"昵称", @"用户类型", @"真实姓名", @"手机号", @"邮箱", @"用户介绍", @"客户代码", @"客户注册时间", @"客户等级", @"公司id",@"公司名称", @"营业执照扫描件", @"有效证件号码", @"网店地址链接", @"产品类别", @"产品风格", @"付款方式及账期", @"付款账号/卡号", @"账号状态", @"专属客服", @"推荐人", @"积分"];
    self.infoArray = [self.infoModel keyValues].allKeys;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)requestData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData getUserDetail:[UIUtil toJsonString:dic] withBlock:^(UserInfoModel *model, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.infoModel = model;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableFootview {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"chooseMyProduct"] forState:UIControlStateNormal];
    [button setTitle:@"退出账号" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.frame = CGRectMake((SCREEN_WIDTH-SCREEN_WIDTH*0.7)/2, 8, SCREEN_WIDTH*0.7, 32);
    [button addTarget:self action:@selector(exitLoginButton) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 48)];
    [view addSubview:button];
    self.tableView.tableFooterView = view;
}

#pragma mark  退出登录 同时从本地删除
- (void)exitLoginButton {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData loginoutParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"退出失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
            self.view.window.rootViewController = nav;
            [UserModel sharedInstance].userName = nil;
            [UserModel sharedInstance].userToken = nil;
        }
    }];
}

#pragma mark 数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 0?_dataArray.count:1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"Cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            _iconImgButton = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 50, 50)];
            [cell addSubview:_iconImgButton];
            [_iconImgButton setImageWithURL:[NSURL URLWithString:self.infoModel.headPortraits] placeholderImage:[UIImage imageNamed:@"tupian"]];
            _iconImgButton.layer.cornerRadius = 25;
            _iconImgButton.clipsToBounds = YES;
            cell.detailTextLabel.text = @"更换头像";
        } else {
            cell.textLabel.text = _dataArray[indexPath.row];
            if (indexPath.row == 1) {
                cell.detailTextLabel.text = self.infoModel.userName;
            } else if (indexPath.row == 2) {
                cell.detailTextLabel.text = self.infoModel.nickName;
            } else if (indexPath.row == 3) {
                cell.detailTextLabel.text = [self.infoModel.userType integerValue]==1?@"买家":[self.infoModel.userType integerValue]==2?@"设计师":[self.infoModel.userType integerValue]==4?@"厂长":[self.infoModel.userType integerValue]==8?@"工人":@"工巢员工";
            } else if (indexPath.row == 4) {
                cell.detailTextLabel.text = self.infoModel.realName;
            } else if (indexPath.row == 5) {
                cell.detailTextLabel.text = self.infoModel.cellPhone;
            } else if (indexPath.row == 6) {
                cell.detailTextLabel.text = self.infoModel.email;
            } else if (indexPath.row == 7) {
                cell.detailTextLabel.text = self.infoModel.introduction;
            } else if (indexPath.row == 8) {
                cell.detailTextLabel.text = self.infoModel.userCode;
            } else if (indexPath.row == 9) {
                cell.detailTextLabel.text = self.infoModel.userRegistrationTime;
            } else if (indexPath.row == 10) {
                cell.detailTextLabel.text = self.infoModel.userGrade;
            } else if (indexPath.row == 11) {
                cell.detailTextLabel.text = self.infoModel.firmId;
            } else if (indexPath.row == 12) {
                cell.detailTextLabel.text = self.infoModel.firmName;
            } else if (indexPath.row == 13) {
                cell.detailTextLabel.text = self.infoModel.businessLicenseScanning;
            } else if (indexPath.row == 14) {
                cell.detailTextLabel.text = self.infoModel.identificationNumber;
            } else if (indexPath.row == 15) {
                cell.detailTextLabel.text = self.infoModel.storeAddressLink;
            } else if (indexPath.row == 16) {
                cell.detailTextLabel.text = self.infoModel.saleProductCategory;
            } else if (indexPath.row == 17) {
                cell.detailTextLabel.text = self.infoModel.saleProductStyle;
            } else if (indexPath.row == 18) {
                cell.detailTextLabel.text = self.infoModel.payTermAndPayDay;
            } else if (indexPath.row == 19) {
                cell.detailTextLabel.text = self.infoModel.payAccount;
            } else if (indexPath.row == 20) {
                cell.detailTextLabel.text = [self.infoModel.accountStatus integerValue]==1000?@"正常":[self.infoModel.accountStatus integerValue]==1001?@"待激活":[self.infoModel.accountStatus integerValue]?@"待审核":@"注销";
            } else if (indexPath.row == 21) {
                cell.detailTextLabel.text = self.infoModel.saleStaffNumber;
            } else if (indexPath.row == 22) {
                cell.detailTextLabel.text = self.infoModel.advisor;
            } else if (indexPath.row == 23) {
                cell.detailTextLabel.text = self.infoModel.integral;
            } 
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    } else {
        cell.textLabel.text = @"收货地址管理";
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.3, 8, SCREEN_WIDTH*0.6, 30)];
        [cell addSubview:label];
        label.textAlignment = NSTextAlignmentRight;
        label.textColor = [UIUtil colorWithHexString:@"#9a9a9a"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.textColor = [UIUtil colorWithHexString:@"#929292"];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请选择图片来源" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
            alertView.delegate = self;
            [alertView show];
        }
        if (indexPath.row != 0) {
            if (indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7 || indexPath.row == 2 || indexPath.row == 12 || indexPath.row == 14 || indexPath.row == 15 || indexPath.row == 16 || indexPath.row == 19) {
                EditMessagePerVC *editMessage = [[EditMessagePerVC alloc] init];
                [self.navigationController pushViewController:editMessage animated:YES];
                editMessage.pathStringValue = [tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text;
                editMessage.model = self.infoModel;
                editMessage.titleString = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
                editMessage.infoBlock = ^(NSString *info) {
                    [self.tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = info;
                };
            }
        }
    } else {
        AddressViewController *receiveView = [[AddressViewController alloc] init];
        receiveView.addressTitle = @"收货地址管理";
        receiveView.ifModify = YES;
        [self.navigationController pushViewController:receiveView animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 1?10:0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        view.backgroundColor = [UIUtil colorWithHexString:@"#eeecf4"];
        return view;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0 && indexPath.row==0) {
        return 70;
    }
    return 44;
}

#pragma mark 更换头像
- (void)changeIconButton:(UIButton *)button {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请选择图片来源" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    alertView.delegate = self;
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==1) {
        UIImagePickerController *ipc=[[UIImagePickerController alloc]init];
        //判断当前设备能否拍照
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            return;
        }
        ipc.sourceType=UIImagePickerControllerSourceTypeCamera;
        ipc.delegate=self;
        ipc.allowsEditing=YES;
        [self presentViewController:ipc animated:YES completion:nil];
    }
    else if (buttonIndex==2){
        UIImagePickerController *ipc=[[UIImagePickerController alloc]init];
        ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        ipc.delegate=self;
        ipc.allowsEditing=NO;
        [self presentViewController:ipc animated:YES completion:nil];
    }
    
}

#pragma mark imagePickeControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //把图片保存到相册,保存完了执行image:didFinishSavingWithError:contextInfo:方法
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    _iconImgButton.image = image;
//    [_iconImgButton setBackgroundImage:image forState:UIControlStateNormal];
    [self uploadFile:image];
}

- (void)uploadFile:(UIImage *)imageData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData fileUploadParameters:[UIUtil toJsonString:dic] imageData:imageData withBlock:^(NSString *fileId, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"图片上传失败":msg dismissBlock:nil];
            }
        } else {
            NSMutableDictionary *modelDic = self.infoModel.keyValues;
            [modelDic setValue:fileId forKey:@"headPortraits"];
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[UserModel sharedInstance].userToken,@"token", nil];
            [dic setValuesForKeysWithDictionary:modelDic];
            [RequestData updateUserInfo:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
                if (error) {
                    if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                        [UIUtil tokenOverdue:self msg:msg];
                    } else {
                        [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交失败":msg dismissBlock:nil];
                    }
                } else {
                    if (_headBlock) {
                        _headBlock (imageData, self.infoModel.nickName);
                    }
                    [[ESHUDView sharedInstance] showSuccessMessage:msg==nil?@"提交成功":msg dismissBlock:nil];
                }
            }];
        }
    }];
}

@end
